﻿<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>Lazy cache sample app</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"> </script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"> </script>
    <![endif]-->
</head>
<body>
    <div class="container">
        <div class="centre-box">
            <div class="counter pull-right"><span class="counter-val">0</span> Database query(s)</div>

            <h1>Sample app to demonstrate using an cache in your API to save database SQL queries and speed up API calls</h1>

            <p>
                Every 3 seconds we fetch the current time from the database, however because the sql query 
                result is cached on the server on the first call, the time stays the same untill you clear
                the cache and no more SQL queries are made. <br />
                <br />
                
                After you clear the cache you should see the time change because a real SQL query is made.<br /> 
                <br />
                
                Also note how real SQL queryies are slower than cache hits.
            </p>

            <div class="button-bar">
                <button class="btn btn-default btn-primary btn-clear-cache">Clear Cache</button>
            </div>

            <label>Log</label>
            <p class="log"></p>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <script>
        // util for n digit numbers with leading zeros
        Number.prototype.pad = function (len) {
            return (new Array(len + 1).join("0") + this).slice(-len);
        }
    </script>
    <script>
        "use strict";

        (function () {
            var app = {
                log: function (message) {
                    var now = new Date();
                    var prefix = "[" + now.getHours().pad(2) + ":" + now.getMinutes().pad(2) + ":" + now.getSeconds().pad(2) + "] ";
                    var currentLog = $(".log").text();
                    $(".log").text(prefix + message + "\n" + currentLog);
                },

                getDbTime: function () {
                    return $.get("/api/dbtime");
                },

                updateDbQueryCount: function () {
                    return $.get("/api/dbQueries")
                        .done(function (data) {
                            $(".counter-val").text(data);
                        });
                },

                updateLogWithTime: function (dbTime, duration) {
                    var message = "API reports that the time now in the database is " + dbTime.timeNowInTheDatabase + " (" + duration + "ms)";
                    app.log(message);
                },

                clearCache: function () {
                    $.ajax({
                        method: "DELETE",
                        url: "/api/dbtime"
                    })
                        .done(function (data) {
                            app.log(data.message);
                        });
                },

                updateTimeEvent: function () {

                    var start_time = new Date().getTime();

                    return app.getDbTime()
                        .done(function(data) {
                            var duration = new Date().getTime() - start_time;
                            app.updateLogWithTime(data, duration);
                        })
                        .then(app.updateDbQueryCount);
                },

                startPollingForTime: function () {
                    var threeSecs = 3000;
                    setInterval(app.updateTimeEvent, threeSecs);
                },

                bindEvents: function () {
                    $(".btn-clear-cache").click(app.clearCache);

                    $(document).ajaxError(function (event, request, settings) {
                        app.log("Error requesting page " + settings.url);
                    });
                }

            };

            // setup the application
            app.bindEvents();

            // fetch the db time now
            app.log("Starting app... Fetching the current time from SQL server every 3 secs");
            app.updateTimeEvent()
                .then(app.startPollingForTime);
        })();

    </script>

    <style>
        body {
            background-color: #EEEEEE;
            padding-bottom: 40px;
            padding-top: 40px;
        }

        .centre-box {
            margin: 0 auto;
            max-width: 850px;
            padding: 15px;
        }

        .log {
            font-family: consolas;
            white-space: pre-line;
        }

        .button-bar {
            min-height: 3em;
        }

        .counter {
            margin: -3em 0 0 0;
            padding: 0.5em;
            max-width: 6em;
            background-color: darkslategrey;
            color: lightskyblue;
            text-align: center;
            font-size: 1.2em;
            font-weight: bold;
        }
    </style>
</body>
</html>